using UnityEngine;
using Framework;
using System.Collections.Generic;
using LuaInterface;


[DisallowMultipleComponent]
public class AnimationEventWrap : MonoBehaviour
{
    private Dictionary<string, GeneralCallBack> eventCallbackDict = new Dictionary<string, GeneralCallBack>();

    public void AddEventListener(string eventName, LuaFunction luaCallback, LuaTable luaTarget)
    {
        GeneralCallBack eventCallback;
        eventCallbackDict.TryGetValue(eventName, out eventCallback);
        GeneralCallBack.GetOrReUse(ref eventCallback, luaCallback, luaTarget);
        eventCallbackDict[eventName] = eventCallback;
    }

    public void RemoveEventListener(string eventName)
    {
        GeneralCallBack eventCallback;
        eventCallbackDict.TryGetValue(eventName, out eventCallback);
        if (eventCallback != null)
        {
            GeneralCallBack.RecycleInst(ref eventCallback);
        }
        eventCallbackDict[eventName] = null;
    }

    public void RemoveAllEventListener()
    {
        foreach (var item in eventCallbackDict)
        {
            GeneralCallBack eventCallback = item.Value;
            if (eventCallback != null)
            {
                GeneralCallBack.RecycleInst(ref eventCallback);
            }
        }
        eventCallbackDict.Clear();
    }

    private void DispatchEvent(string eventName)
    {
        GeneralCallBack eventCallback;
        if (eventCallbackDict.TryGetValue(eventName, out eventCallback))
        {
            if (eventCallback != null)
            {
                GeneralCallBack.Invoke(ref eventCallback);
            }
        }
    }

    private void OnDestroy()
    {
        RemoveAllEventListener();
    }
}
